package com.enation.app.javashop.core.geo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.enation.app.javashop.core.geo.model.*;
import com.enation.app.javashop.core.geo.service.TencentManager;
import com.enation.app.javashop.framework.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author JFeng
 * @date 2019/10/22 9:45
 */
@Service
public class TencentManagerImpl implements TencentManager {


    @Autowired(required = false)
    RestTemplate restTemplate;

    private final static String Tencent_MAP_KEY_POI = "62ZBZ-HUJLX-FN747-TGQUN-VKIZ3-KHFNL";



    /**
     * 根据POI逆解析 地址逆解析
     * https://restapi.amap.com/v3/geocode/regeo?output=xml&location=116.310003,39.991957&key=<用户的key>&radius=1000&extensions=all
     *
     * @param lng,lat 121.297619,31.204124    lat<纬度>,lng<经度>
     * @return 返回poi详细信息
     */
    @Override
    public TencentLocation parseLatLng(Double lng, Double lat) {
        if (lng == null || lat == null) {
            return new TencentLocation();
        }
        String lngLat = lat + "," + lng;
        StringBuilder requestParam = new StringBuilder("https://apis.map.qq.com/ws/geocoder/v1/");
        requestParam.append("?key=" +Tencent_MAP_KEY_POI)
                .append("&get_poi=1")
                .append("&location="+lngLat);
        String result = restTemplate.getForObject(requestParam.toString(), String.class);
        TencentParseLatLngResponse parseLatLngResponse = JSON.parseObject(result, new TypeReference<TencentParseLatLngResponse>() {
        });
        // 解析四级地址
        AddressReference addressReference = parseLatLngResponse.getResult().getAddressReference();
        if(addressReference == null){
            // 衢山镇 中心坐标
            String origin = "122.365014,30.448477";
            int range = 10; //单位公里
            // 衢山镇 中心点 到 传来的坐标的距离
            double distance = countDrivingDistance(origin, lngLat);
            // 固定范围大于等于 计算距离 在衢山镇
            if(range >= distance){
                requestParam = new StringBuilder("https://apis.map.qq.com/ws/geocoder/v1/");
                requestParam.append("?key=" +Tencent_MAP_KEY_POI)
                        .append("&get_poi=1")
                        .append("&location="+origin);
                result = restTemplate.getForObject(requestParam.toString(), String.class);
                parseLatLngResponse = JSON.parseObject(result, new TypeReference<TencentParseLatLngResponse>() {
                });
            }
        }
        // 封装四级地址
        String town = addressReference.getTown();
        if(StringUtil.notEmpty(town)){
            JSONObject townJson = JSON.parseObject(town);
            String townTitle = townJson.getString("title");
            AddressComponent addressComponent = parseLatLngResponse.getResult().getAddressComponent();
            addressComponent.setTownshipStr(townTitle);
        }
        return parseLatLngResponse.getResult();
    }

    @Override
    public List<Pois> inputtips(String keyword,String region) {
        if (StringUtils.isEmpty(keyword)) {
            return new ArrayList<>();
        }
        StringBuilder requestParam = new StringBuilder("https://apis.map.qq.com/ws/place/v1/suggestion");
        requestParam.append("?key=" +Tencent_MAP_KEY_POI)
                .append("&region="+region)
                .append("&keyword="+keyword);
        String result = restTemplate.getForObject(requestParam.toString(), String.class);
        ParseKeywordResponse parseKeywordResponse = JSON.parseObject(result, new TypeReference<ParseKeywordResponse>() {
        });

        List<Pois> pois = parseKeywordResponse.getTips();
        List<Pois> correctPois =new ArrayList<>();
        if(!CollectionUtils.isEmpty(pois)){
            for (Pois poi : pois) {
                String location = poi.getLocation();
                if(!location.equals("[]")){
                    String[] locationArray = poi.getLocation().split(",");
                    poi.setLng(Double.valueOf(locationArray[0]));
                    poi.setLat(Double.valueOf(locationArray[1]));
                    correctPois.add(poi);
                }
            }
        }
        return correctPois;
    }


    /**
     * 计算距离
     * @param origin 出发点 经度在前，纬度在后
     * @param destination 到达点 经度在前，纬度在后
     * @return 距离(米)
     */
    @Override
    public double countDrivingDistance(String origin, String destination) {
        StringBuilder sb = new StringBuilder("https://apis.map.qq.com/ws/direction/v1/driving/");
        sb.append("?key=" + Tencent_MAP_KEY_POI)
                .append("&from=" + origin)
                .append("&to=" + destination)
                .append("&output=json");
        String resultJson = restTemplate.getForObject(sb.toString(), String.class);
        JSONObject jsonObject = JSON.parseObject(resultJson);
        if(jsonObject != null && "0".equals(jsonObject.getString("status"))){
            JSONObject result = jsonObject.getJSONObject("result");
            JSONObject route = result.getJSONArray("routes").getJSONObject(0);
            return Double.valueOf(route.getString("distance"));
        }
        return 0;
    }


}
